package com.lagou.edu.controller;

import com.lagou.edu.feign.EmailFeign;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.utils.LagouUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;

/**
 * @Author 梅松
 * @Date 2021/10/17 11:22
 */
@RestController
@RequestMapping("/code")
@Validated
public class CodeController {
    @Autowired
    private CodeService codeService;
    @Autowired
    private EmailFeign emailFeign;
    @Value("${code.expire-time}")
    private int expire_time;


    /**
     * 生成验证码
     * @param email
     * @return
     */
    @GetMapping("/create")
    public Result create(@NotBlank String email){
       //1、生成验证码
        String code = LagouUtils.getCheckCode();
       //2、发送邮件
        Result<Boolean> result = emailFeign.email(email, code,expire_time);
        if((boolean) result.getData() == false){
            return Result.fail("发送邮件失败");
        }
        //3、保存到数据库,先删除再保存
        codeService.deleteCode(email);
        codeService.saveCode(code,email);
        return Result.ok("发送验证码成功");
    }

    /**
     * 校验验证码
     * @param email
     * @param code
     * @return
     */
    @GetMapping("/checkCode/{email}/{code}")
    public Result<Boolean> checkCode(@PathVariable String email,@PathVariable String code){
        return codeService.checkCode(email,code);
    }

    /**
     *  删除code
     * @param email
     * @return
     */
    @DeleteMapping("/deleteCode/{email}")
    public Result deleteCode(@PathVariable String email){
        return codeService.deleteCode(email);
    }
}
